<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <img src="../../../assets/images/avatar.jpg" alt="" v-if="url === ''" />
      <img :src="url" alt="" v-else />
      <div class="btn-box">
        <input type="file" style="display: none" ref="fileRef" @change="preview" />
        <el-button type="primary" icon="el-icon-plus" @click="$refs.fileRef.click()" diaplay>选择图片</el-button>
        <el-button type="success" :disabled="url === ''" icon="el-icon-upload" @click="uplaod">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import { updateAvatarAPI } from '@/APl/user.js'
export default {
  data() {
    return {
      url: ''
    }
  },
  methods: {
    preview(e) {
      if (e.target.files.length > 0) {
        const fileObj = e.target.files[0]
        // console.log(fileObj)
        // this.url = URL.createObjectURL(fileObj)
        const fr = new FileReader()
        fr.readAsDataURL(fileObj)
        fr.onload = () => {
          this.url = fr.result
        }
      } else {
      }
    },
    async uplaod() {
      const { data: res } = await updateAvatarAPI(this.url)
      if (res.code === 0) {
        this.$message.success(res.message)
        this.$store.dispatch('user/getUser')
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  font-size: 13px;
  img {
    width: 300px;
    height: 300px;
    object-fit: cover;
  }
  .btn-box {
    margin-top: 10px;
  }
}
</style>
